//
//  AuthorityTransferView.m
//  TaiHao
//
//  Created by rzm on 16/6/3.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SampuxAuthorityTransferView.h"
#import "IsValidateOrNot.h"

@interface SampuxAuthorityTransferView ()<UITextFieldDelegate>

@property (nonatomic, strong) UITextField *nameF;
@property (nonatomic, strong)  UIView *backView;

@end
@implementation SampuxAuthorityTransferView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(OwnChange:) name:NOTIFICATION_RESPONSE_CHANGE_DEVICE_OWN object:nil];
        [self loadUI];
    }
    return self;
}

- (void)loadUI
{
    CGFloat font = 8.;
    if (IS_IPHONE_4_OR_LESS) {
        font = 14.;
    }else if (IS_IPHONE_5_OR_LESS)
    {
        font = 14.;
    }else if (IS_IPHONE_6)
    {
        font = 16.;
    }else
    {
        font = 17.;
    }
//    
    UIView *view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self addSubview:view];
    view.backgroundColor = THBlackAlplaColor(0.6);
    view.alpha = 1;
    
   UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(kScreenWidth*0.08, self.height * 0.3 , kScreenWidth*0.84, kScreenHeight  * 0.4)];
    [view addSubview:backView];
    self.backView = backView;
    backView.backgroundColor = THWhiteAlplaColor(0.48);
    [backView setCorner:5];
    
    
    UILabel *lab = [UILabel createLabelWithText:@"权限转移" frame:CGRectMake(0, 0, backView.width, backView.height * 0.2) font:THFont(font)];
    lab.textAlignment = NSTextAlignmentCenter;
    lab.textColor = THSystemWhiteColor;
    [backView addSubview:lab];
    lab.backgroundColor = THDeFaultBlueColor;

    UIButton *warnBtn = [UIButton createButtonWithImage:imageNamed(@"user")];
    warnBtn.frame = CGRectMake(backView.width *0.05 ,lab.bottom + Sampux6WScale(10), backView.width*0.9, Sampux6HScale(30));
    [backView addSubview:warnBtn];
    [warnBtn setTitle:@"警告:" forState:UIControlStateNormal];
    warnBtn.titleLabel.font = THFont(font);
    warnBtn.titleEdgeInsets =  UIEdgeInsetsMake(0, 8, 0, 0);
    [warnBtn setTitleColor:THBlackAlplaColor(0.6) forState:UIControlStateNormal];
    warnBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [warnBtn setImage:imageNamed(@"warnTip") forState:UIControlStateNormal];
    
    NSString *warnStr = @"此操作为不可逆行为，确认后将失去对这台设备的所有权，接管方将接管此设备。";
    CGSize maxSize = CGSizeMake(backView.width - backView.width *0.05, MAXFLOAT);
    CGSize strSize = [SampuxGlobalTool getSizeWithString:warnStr andFont:THFont(font - 2) andMaxSize:maxSize];
    
    UILabel *warnLab = [UILabel createLabelWithText:warnStr frame:CGRectMake(backView.width *0.05, warnBtn.bottom + Sampux6HScale(2), backView.width * 0.9, strSize.height) font:THFont(font - 2)];
    warnLab.font = THFont(font -2);
    warnLab.numberOfLines = 0;
    warnLab.textColor = THBlackAlplaColor(0.6);
    [backView addSubview:warnLab];
    
    _nameF = [UITextField createTextFieldWithRect:CGRectMake(backView.width/2 - Sampux6WScale(250)/2 , CGRectGetMaxY(warnLab.frame) + Sampux6HScale(20),  Sampux6WScale(250), Sampux6HScale(SampuxCustomH)) andPlaceholder:@"输入接收方的用户名" andLeftImage:@"make-user"];
        [backView addSubview:_nameF];
    [UIView createLineViewInbottom:_nameF];
    _nameF.delegate = self;
    
    UIButton *yesBtn = [UIButton createButtonWithTitle:@"确定" frame:CGRectMake(backView.width *0.2,_nameF.bottom + Sampux6HScale(30), backView.width* 0.6, backView.height * 0.15) titleFont:THFont(font) titleColor:THDeFaultBlueColor];
    [backView addSubview:yesBtn];
    [yesBtn addTarget:self action:@selector(yesBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [yesBtn setCorner: yesBtn.height/2];
    yesBtn.layer.borderWidth = 1;
    yesBtn.layer.borderColor = THWhiteAlplaColor(0.6).CGColor;
    
    backView.height = yesBtn.bottom + Sampux6HScale(20);
}

- (void)yesBtnClick
{
    
    BOOL isEmail = [IsValidateOrNot isValidateEmail:self.nameF.text];
    BOOL isMobile = [IsValidateOrNot isValidateMobile:self.nameF.text];
    
    if ([self.nameF.text isEqualToString:@""] || self.nameF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
//        [MBProgressHUD showError:@"用户名必须为手机号或者邮箱"];
    }else
    {
        if (!isMobile&&!isEmail)
        {
            [SVProgressHUD showErrorWithStatus:@"用户名错误"];
//            [MBProgressHUD showError:@"用户名错误"];
        }else
        {
            [self removeView];
            [GBInterMaster_CommForSystem requestDeviceOwnChange:0 withDeviceAccount:self.model.deviceAccount withUserAccount:self.nameF.text];
            //给后台传值
        }
    }
}

- (void)removeView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        _nameF.text = @"";
        [self removeFromSuperview];
    });
}

- (void)OwnChange:(NSNotification *)notification
{
    [SVProgressHUD dismiss];
//    [MBProgressHUD hideHUD];
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"OwnChange == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00){
        [[NSNotificationCenter defaultCenter]postNotificationName:@"setOwnChangeSuccess" object:nil];
        if (self.transferBlock) {
            self.transferBlock();
        }
        [SVProgressHUD showSuccessWithStatus:@"所有者权限转移成功"];

    }else
    {
        [SPResponseCodePrompt responseCodePrompt:responseCode];
        [SVProgressHUD showErrorWithStatus:@"所有者权限转移失败"];
//        [MBProgressHUD showError:@"所有者权限转移失败"];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    CGFloat ly = [touch locationInView: self.backView].y;
    if ( ly < 0 || ly > self.backView.height ) { //点标题栏也会消失，点其他地方捕捉不到了
        [self removeView];
    }
    [super touchesBegan:touches withEvent:event];
}

#pragma -mark 输入框代理
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    CGFloat keyboardHeight = 216.0f;
    self.frame = CGRectMake(0, - keyboardHeight/3, self.width, self.height);
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
